import store from '@/store';
import { RISK_STATUS } from '@/constants/risk-assessment-template';

// 合并多个问卷模板的所有问题 AND 生成页面作答人数组 AND 生成风险数组
export function processSurveyQuestion(surveyArray: any[]) {
  let pageNo = 1;
  const answerArr = [];
  const questionArr = [];
  const riskArr = [];

  surveyArray?.forEach((item) => {
    Object.entries(item.question?.allRisk ?? {}).forEach(([key, value]: [string, any]) => {
      riskArr.push({ qsName: key, rsTemplates: value });
    });
    const pages = item.question && item.question.pages;
    if (pages) {
      pages.forEach((page) => {
        page.title = `${pageNo}. ${page.title ?? page.name}`;
        const questionNameArr = [];
        const obj: { content: number; questionName: string; name: string } = {
          content: undefined,
          questionName: '',
          name: page.name,
        };
        let questionNo = 0;
        page.elements?.forEach((element) => {
          if (element.type !== 'panel') {
            questionNameArr.push(element.name);
            element.title = `${pageNo}.${(questionNo += 1)} ${element.title ?? element.name}`;
          }
          element.elements?.forEach((panel_element) => {
            questionNameArr.push(panel_element.name);
            panel_element.title = `${pageNo}.${(questionNo += 1)} ${panel_element.title ?? panel_element.name}`;
          });
        });
        obj.questionName = questionNameArr.join(',');
        answerArr.push(obj);
        questionArr.push(page);
        pageNo += 1;
      });
    }
  });

  return { questionArr, answerArr, riskArr };
}

// 生成页面作答人数组
export function generateAnswerArray(pageArray: any[]) {
  if (!pageArray) return [];

  const answerArr = [];
  pageArray.forEach((page) => {
    const questionNameArr = [];
    const obj: { content: number; questionName: string; name: string } = {
      content: undefined,
      questionName: '',
      name: page.name,
    };
    page.elements?.forEach((element) => {
      if (element.type !== 'panel') questionNameArr.push(element.name);
      element.elements?.forEach((panel_element) => {
        questionNameArr.push(panel_element.name);
      });
    });
    obj.questionName = questionNameArr.join(',');
    answerArr.push(obj);
  });

  return answerArr;
}

// 生成树形结构数组
export function generateTreeArray(pageArray: any[]) {
  if (!pageArray) return [];

  const tree = [];
  pageArray.forEach((page) => {
    const children = [];
    const obj: { label: string; value: string; children: any[] } = {
      label: page.title,
      value: page.name,
      children,
    };
    page.elements?.forEach((element) => {
      if (element.type !== 'panel')
        children.push({
          label: element.title,
          value: element.name,
        });
      element.elements?.forEach((panel_element) => {
        children.push({
          label: panel_element.title,
          value: panel_element.name,
        });
      });
    });
    tree.push(obj);
  });

  return tree;
}

// 根据流转数组来处理问卷问题是否只读，添加收藏数据，初始化问题对象
export function generateSurveyJsonAddReadonly(
  qsInformation: any,
  [flagQuestionArr, assignedQuestionArr, uploadFileArr, messageArr, historyArr]: any[],
) {
  if (!qsInformation) return {};
  // 当前用户id
  const cId = store.getters['user/cId'];
  // 当前是否是问卷发起人
  const isInitiator = cId === qsInformation.initiatedId;
  // 当前是否是问卷作答人
  const isRespondent = cId === qsInformation.answerId;
  // console.log(cId, isInitiator, isRespondent);

  const newObject = {};
  const newJson = JSON.parse(JSON.stringify(qsInformation.question));

  // 被标记的题目数组
  const flagNameArr = flagQuestionArr.filter((i) => i.content === '1');
  // 当前是问卷作答人不需要作答的题目数组
  let disabledNameArr = [];
  if (isRespondent) {
    disabledNameArr = assignedQuestionArr.filter((i) => Number(i.content) !== cId).map((i) => i.questionName);
  }

  // 当前不是问卷作答人需要作答的题目数组
  let unDisabledNameArr = [];
  if (!isRespondent) {
    unDisabledNameArr = assignedQuestionArr.filter((i) => Number(i.content) === cId).map((i) => i.questionName);
  }

  // 已流转问题对象
  const assignedQuestionObj = {};
  assignedQuestionArr.forEach((item) => {
    assignedQuestionObj[item.questionName] = item;
  });

  newJson.pages.forEach((page) => {
    page.elements?.forEach((element) => {
      if (element.type !== 'panel') {
        // element = isInitiator ? JSON.parse(JSON.stringify(element)) : element;
        element.fileNum = 0;
        element.messageNum = 0;
        element.historyNum = 0;
        newObject[element.name] = element;
        if (!isInitiator) {
          if (isRespondent && disabledNameArr.includes(element.name)) {
            element.readOnly = true;
            newObject[element.name].assignedName = assignedQuestionObj[element.name].name;
          }
          if (!isRespondent && !unDisabledNameArr.includes(element.name)) {
            element.readOnly = true;
            newObject[element.name].assignedName = assignedQuestionObj[element.name]
              ? assignedQuestionObj[element.name].name
              : qsInformation.answerName;
          }
        }
        if (element.choices) {
          element.choices = element.choices.map((i) => {
            if (i instanceof Object) {
              return { value: i.value, label: i.text, text: i.text };
            }
            return { value: i, label: i, text: i };
          });
        }
      }
      element.elements?.forEach((panel_element) => {
        // panel_element = isInitiator ? JSON.parse(JSON.stringify(panel_element)) : panel_element;
        panel_element.fileNum = 0;
        panel_element.messageNum = 0;
        panel_element.historyNum = 0;
        newObject[panel_element.name] = panel_element;
        if (!isInitiator) {
          if (isRespondent && disabledNameArr.includes(panel_element.name)) {
            panel_element.readOnly = true;
            newObject[panel_element.name].assignedName = assignedQuestionObj[panel_element.name].name;
          }
          if (!isRespondent && !unDisabledNameArr.includes(panel_element.name)) {
            panel_element.readOnly = true;
            newObject[panel_element.name].assignedName = assignedQuestionObj[panel_element.name]
              ? assignedQuestionObj[panel_element.name].name
              : qsInformation.answerName;
          }
        }
        if (panel_element.choices) {
          panel_element.choices = panel_element.choices.map((i) => {
            if (i instanceof Object) {
              return { value: i.value, label: i.text, text: i.text };
            }
            return { value: i, label: i, text: i };
          });
        }
      });
    });
  });

  if (isInitiator) {
    Object.keys(newObject).forEach((key) => {
      if (assignedQuestionObj[key]) {
        if (Number(assignedQuestionObj[key].content) !== qsInformation.initiatedId) {
          newObject[key].assignedName = assignedQuestionObj[key].name;
        }
      } else if (!isRespondent) {
        newObject[key].assignedName = qsInformation.answerName;
      }
    });
  }

  flagNameArr.forEach((item) => {
    if (newObject[item.questionName]) newObject[item.questionName].isFlag = true;
  });

  uploadFileArr.forEach((item) => {
    if (newObject[item.questionName]) newObject[item.questionName].fileNum += 1;
  });

  messageArr.forEach((item) => {
    if (newObject[item.questionName]) newObject[item.questionName].messageNum += 1;
  });

  historyArr.forEach((item) => {
    if (newObject[item.questionName]) newObject[item.questionName].historyNum += 1;
  });

  return { newJson, newObject };
}

// 根据数过滤出新的surveyJson
export function generateFilterSurveyJson(surveyJson, activeNodeName) {
  const newJson = JSON.parse(JSON.stringify(surveyJson));
  newJson.pages = newJson.pages?.filter((page) => {
    if (!activeNodeName.includes(page.name)) return false;
    page.elements = page.elements.filter((element) => {
      if (element.elements) {
        element.elements = element.elements.filter((panel_element) => {
          if (!activeNodeName.includes(panel_element.name) && !panel_element.visibleIf) return false;
          return true;
        });
        return true;
      }
      if (!activeNodeName.includes(element.name) && !element.visibleIf) return false;
      return true;
    });
    return true;
  });

  return newJson;
}

// 根据问题对象和历史答题记录(value)生成新的历史答题记录(label)
export function generateHistoryArray(questionInfo, historyArr) {
  if (!questionInfo) return;

  function processContent(questionInfo, content, item) {
    if (questionInfo.type === 'boolean') {
      if (!questionInfo.valueFalse && content === 'false') content = `答案：${questionInfo.labelFalse ?? '否'}`;
      if (!questionInfo.valueTrue && content === 'true') content = `答案：${questionInfo.labelTrue ?? '是'}`;
      if (content === questionInfo.valueFalse) content = `答案：${questionInfo.labelFalse}`;
      if (content === questionInfo.valueTrue) content = `答案：${questionInfo.labelTrue}`;
    }

    if (questionInfo.type === 'radiogroup') {
      const choice = questionInfo.choices?.find((i) => i.value === content);
      content = `答案：${choice ? choice.text : item}`;
    }

    if (questionInfo.type === 'checkbox') {
      const choiceObj = {};
      questionInfo.choices?.forEach((i) => {
        choiceObj[i.value] = i.text;
      });

      const answerArr = JSON.parse(content).map((i) => (choiceObj[i] ? choiceObj[i] : i));
      content = `答案：\n${answerArr.join('\n')}`;
    }

    if (questionInfo.type === 'file') {
      content = `文件上传：${JSON.parse(content)[0].name}`;
    }

    if (questionInfo.type === 'text' || questionInfo.type === 'comment') {
      content = `答案：${content}`;
    }

    if (questionInfo.type === 'multipletext') {
      const answerObj = JSON.parse(content);

      const entriesArr = [];
      Object.entries(answerObj).forEach(([key, value]) => {
        const choice = questionInfo.items?.find((i) => i.name === key);
        entriesArr.push(`${choice.title ?? choice.name} 答案：${value}`);
      });
      content = entriesArr.join('\n');
    }

    if (questionInfo.type === 'matrix') {
      const rowObj = {};
      const columnObj = {};
      questionInfo.rows.forEach((row) => {
        rowObj[row.value ?? row] = row.text ?? row;
      });
      questionInfo.columns.forEach((column) => {
        columnObj[column.value ?? column] = column.text ?? column;
      });

      const answerObj = JSON.parse(content);
      const entriesArr = [];
      Object.entries(answerObj).forEach(([key, value]: any) => {
        entriesArr.push(`[${rowObj[key]}, ${columnObj[value]}]`);
      });
      content = `答案：\n${entriesArr.join('\n')}`;
    }

    if (questionInfo.type === 'matrixdropdown') {
      questionInfo.rows.forEach((row) => {
        content = content.replaceAll(row.value ?? row, row.text ?? row);
      });
      questionInfo.columns.forEach((column) => {
        content = content.replaceAll(column.name, column.title ?? column.name);
      });

      const answerObj = JSON.parse(content);
      const arr = [];
      Object.keys(answerObj).forEach((row) => {
        Object.keys(answerObj[row]).forEach((column) => {
          arr.push(`[${row}, ${column}] = ${answerObj[row][column]}`);
        });
      });
      content = `答案：\n${arr.join('\n')}`;
    }

    if (questionInfo.type === 'matrixdynamic') {
      questionInfo.columns.forEach((column) => {
        if (!column.title) return;
        content = content.replaceAll(column.name, column.title);
      });

      content = JSON.parse(content).map((o) => {
        const arr = [];
        Object.entries(o).forEach(([key, value]) => {
          arr.push(`${key} = ${value}`);
        });
        return arr.join(', ');
      });
      content = `答案：\n${content.join('\n')}`;
    }

    if (questionInfo.type === 'paneldynamic') {
      const questionNameObj = {};
      questionInfo.templateElements.forEach((i) => {
        questionNameObj[i.name] = i;
      });

      let answerArr = JSON.parse(content);
      answerArr = answerArr.map((o) => {
        const arr = [];
        Object.entries(o).forEach(([questionName, answerObj]) => {
          if (typeof answerObj === 'object') answerObj = JSON.stringify(answerObj);
          arr.push(
            `${questionNameObj[questionName].title ?? questionNameObj[questionName].name}\n${processContent(
              questionNameObj[questionName],
              answerObj,
              answerObj,
            )}`,
          );
        });
        return arr.join('\n');
      });

      content = answerArr.join('\n-------------------------------------------------------------------\n');
    }

    return content;
  }

  historyArr.forEach((item) => {
    item.content = processContent(questionInfo, item.content, item);
  });

  return historyArr;
}

// 校验问卷问题
export function validateQuestion(questionObj, answerObj, isInitiator = false, component) {
  let result = true;

  const entriesArr = Object.entries(questionObj);
  if (isInitiator) {
    entriesArr.forEach(([key, value]: [string, any]) => {
      questionObj[key].isError = false;
      if (answerObj[key] instanceof Array) answerObj[key].sort();
      if (!value.unVisible && value.isRequired && answerObj[key] === undefined) {
        result = false;
        questionObj[key].isError = true;
      }
    });
  }
  if (!isInitiator) {
    entriesArr.forEach(([key, value]: [string, any]) => {
      questionObj[key].isError = false;
      if (answerObj[key] instanceof Array) answerObj[key].sort();
      if (!value.unVisible && !value.readOnly && value.isRequired && answerObj[key] === undefined) {
        result = false;
        questionObj[key].isError = true;
      }
    });
  }
  if (component) component.$forceUpdate();

  return result;
}

// 校验风险等级是否存在不确定风险
export function validateRiskLevel(riskObj) {
  try {
    Object.values(riskObj).forEach((risk: any) => {
      if (risk.level === RISK_STATUS.TO_BE_CONFIRMED) throw new Error('false');
    });
    return true;
  } catch (error) {
    return false;
  }
}
